package com.erp.auto.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.auto.domain.ErpAutoPulishProductProject;
import com.erp.auto.domain.ErpAutoSellerStoreConfigErrorCategory;
import com.erp.auto.domain.dto.ErrorProductDto;
import com.erp.auto.mapper.ErpAutoPulishProductProjectMapper;
import com.erp.auto.mapper.ErpAutoPulishProductProjectTaskMapper;
import com.erp.auto.mapper.ErpAutoSellerStoreConfigErrorCategoryMapper;
import com.erp.auto.mapper.ErpAutoSellerStoreConfigMapper;
import com.erp.auto.service.IErpAutoPublishProductProjectService;
import com.erp.auto.service.IErpAutoPulishProductProjectTaskService;
import com.ruoyi.ae.api.RemoteAeCategoryService;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.ae.api.RemoteAeStoreInfoService;
import com.ruoyi.auto.api.domain.ErpAutoSellerStoreConfig;
import com.ruoyi.collect.api.RemoteCollectProductAService;
import com.ruoyi.collect.api.domain.ErpCollectProductA;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.HttpSendUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.ae.api.RemoteAeStoreInfoService;
import com.ruoyi.gather.api.*;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.gather.api.domain.dto.AeAutoProductDto;
import com.ruoyi.auto.api.domain.ErpAutoPulishProductProjectTask;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.gather.api.domain.dto.ComputeFreightDto;
import com.ruoyi.gather.api.domain.vo.ErpCollectProductSkuVo;
import com.ruoyi.shop.api.RemoteSellerStoreFreightTemplateService;
import com.ruoyi.shop.api.RemoteSellerStorePriceTemplateService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.*;
import com.ruoyi.system.api.RemoteDictDataService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * 自动化上架计划Service业务层处理
 *
 * @author erp
 * @date 2023-12-25
 */
@RequiredArgsConstructor
@Service
public class ErpAutoPulishProductProjectTaskServiceImpl implements IErpAutoPulishProductProjectTaskService {

    @Resource
    RestTemplate restTemplate;
    @Resource
    IErpAutoPublishProductProjectService erpAutoPublishProductProjectService;
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    RemotePythonMethodCallService remotePythonMethodCallService;
    @Resource
    RemoteSellerStorePriceTemplateService remoteSellerStorePriceTemplateService;
    @Resource
    RemoteSellerStoreProductService remoteSellerStoreProductService;
    @Resource
    RemoteAeCategoryService remoteAeCategoryService;
    @Resource
    RemoteDictDataService remoteDictDataService;
    @Resource
    RemoteSellerStoreFreightTemplateService remoteSellerStoreFreightTemplateService;
    @Resource
    RemoteAeStoreInfoService remoteAeStoreInfoService;
    @Resource
    RemotePublishProductService remotePublishProductService;
    @Resource
    RemoteCollectProductService remoteCollectProductService;
    @Resource
    RemoteCollectProductAService remoteCollectProductAService;
    @Resource
    RemoteCollectProductBService remoteCollectProductBService;
    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    RemoteProductCategoryBrandService remoteProductCategoryBrandService;
    private final ErpAutoPulishProductProjectTaskMapper erpAutoPulishProductProjectTaskMapper;
    private final ErpAutoSellerStoreConfigErrorCategoryMapper erpAutoSellerStoreConfigErrorCategoryMapper;
    private final ErpAutoPulishProductProjectMapper erpAutoPulishProductProjectMapper;
    private final ErpAutoSellerStoreConfigMapper erpAutoSellerStoreConfigMapper;


    /**
     * 获取当前时间之前的所有未执行的上架计划
     *
     * @param id
     * @return
     */
    @Override
    public R<Object> updatePublishTaskStatusByCurrentTime(String id) {
        List<ErpAutoPulishProductProjectTask> taskList = new ArrayList<>();
        if (ObjectUtils.isNull(id)) {
            //获取当前需要执行的任务列表
            //待执行的，且时间在当前时间到当前时间+1分钟之间的
            //获取当前时间
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化当前时间
            String nowFormatted = now.format(formatter);
            LocalDateTime parse = LocalDateTime.parse(nowFormatted, formatter);
//            LocalDateTime oneDayLater = parse.plusDays(-2);

            // 获取当前时间之前未执行的所有计划
            taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getStatus, 0)
                            .lt(ErpAutoPulishProductProjectTask::getExecutionTime, nowFormatted)
                            .orderByAsc(ErpAutoPulishProductProjectTask::getExecutionTime)
                            .last("limit 100")
            );
        } else {
            taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getId, id)
            );
        }
        if (ObjectUtils.isNull(taskList) || taskList.size() < 1) {
            return R.fail(null);
        }

        for (ErpAutoPulishProductProjectTask task : taskList) {
            task.setStatus(1);
        }
        erpAutoPulishProductProjectTaskMapper.updateBatchById(taskList);
        return R.ok(taskList);

    }

    /**
     * 修改task状态和信息
     *
     * @param id
     * @param status
     * @param msg
     * @return
     */
    @Override
    public R<Object> updateTaskStatus(String id, Integer status, String msg) {
        ErpAutoPulishProductProjectTask task = erpAutoPulishProductProjectTaskMapper.selectById(id);
        if (ObjectUtils.isNull(task)) {
            return R.fail("未查找到该任务");
        } else {
            task.setStatus(status);
            task.setRemark(task.getRemark() + "|" + msg);
            if (msg.contains("从公共库刊登至个人库成功") || msg.contains("个人库原本存在数据")) {
                task.setMqExecutionTime(DateUtils.getTime());
            }
            erpAutoPulishProductProjectTaskMapper.updateById(task);
        }
        return R.ok("修改成功");
    }

    /**
     * 删除待执行的任务
     *
     * @param collectProductId
     * @return
     */
    @Override
    public R<Object> deleteTortListByCollectProductId(String collectProductId) {
        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .eq(ErpAutoPulishProductProjectTask::getCollectProductId, collectProductId)
                        .eq(ErpAutoPulishProductProjectTask::getStatus, 0)
        );
        if (ObjectUtils.isNotNull(taskList) && taskList.size() > 1) {
            for (ErpAutoPulishProductProjectTask task : taskList) {
                task.setStatus(5);
                task.setRemark("产品进入审核中状态，疑似侵权");
            }
            erpAutoPulishProductProjectTaskMapper.updateBatchById(taskList);
        }
        return R.ok();
    }

    /**
     * 重新设置联盟折扣
     * 情况1 将联盟折扣设置异常的处理
     *
     * @return
     */
    @Override
    public R<Object> setCommissionAgainOne() {
        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .like(ErpAutoPulishProductProjectTask::getRemark, "联盟折扣设置异常")
                        .eq(ErpAutoPulishProductProjectTask::getCreateBy, "0")
                        .orderByAsc(ErpAutoPulishProductProjectTask::getCreateTime)
//                        .last("limit 1")
        );
        //将所有子账号店铺转为map
        List<ErpAutoSellerStoreConfig> storeConfigList = erpAutoSellerStoreConfigMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                        .like(ErpAutoSellerStoreConfig::getStoreName, "子账号")
        );
        Map<Long, Object> map = new HashMap<>();
        if (storeConfigList.size() > 0) {
            storeConfigList.forEach(store -> {
                map.put(store.getStoreId(), store.getStoreAlias());
            });
        }

        for (ErpAutoPulishProductProjectTask task : taskList) {
            ErpAutoPulishProductProject project = erpAutoPulishProductProjectMapper.selectById(task.getProjectId());
            String remark = task.getRemark();
            if (Objects.isNull(map.get(task.getStoreId()))) {
                //为空，则代表不是子账号
                BigDecimal afflicateDiscount = null;
                if (project.getIsAfflicateDiscount() == 1) {
                    afflicateDiscount = new BigDecimal(project.getAfflicateDiscount());
                } else {
                    R<Object> templateR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(project.getTemplateId()));
                    String templateString = JSONObject.toJSONString(templateR.getData());
                    ErpSellerStorePriceTemplate template = JSONObject.parseObject(templateString, ErpSellerStorePriceTemplate.class);
                    afflicateDiscount = template.getUnion();
                }
                if (afflicateDiscount.compareTo(BigDecimal.ZERO) > 0) {
                    //调用孙哥方法
                    R<Object> commissionObjectR = remoteSellerStoreService.setCommission(project.getStoreId(), task.getAeProductId(), afflicateDiscount.intValue());
                    if (commissionObjectR.getCode() == 200) {
                        task.setStatus(2);
                        String newRemark = remark.replaceAll("联盟折扣设置异常", "联盟折扣设置成功");
                        task.setRemark(newRemark);
                        erpAutoPulishProductProjectTaskMapper.updateById(task);
                    } else {
                        task.setStatus(3);
                        System.out.println(commissionObjectR.getMsg());
                        String newRemark = remark.replaceAll("联盟折扣设置异常", commissionObjectR.getMsg());
                        task.setRemark(newRemark);
                        erpAutoPulishProductProjectTaskMapper.updateById(task);
                    }
                } else {
                    System.out.println("无需设置联盟折扣");
                }
            } else {
                task.setStatus(2);
                String newRemark = remark.replaceAll("联盟折扣设置异常", "子账号暂不创建联盟折扣");
                task.setRemark(newRemark);
                erpAutoPulishProductProjectTaskMapper.updateById(task);
            }

        }
        return R.ok();
    }

    /**
     * 重新设置联盟折扣
     * 情况2 将用户cookie过期的处理
     *
     * @return
     */
    @Override
    public R<Object> setCommissionAgainTwo() {
        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .like(ErpAutoPulishProductProjectTask::getRemark, "请求速卖通设置失败")
                        .orderByAsc(ErpAutoPulishProductProjectTask::getCreateTime)
//                        .last("limit 1")
        );

        for (ErpAutoPulishProductProjectTask task : taskList) {
            ErpAutoPulishProductProject project = erpAutoPulishProductProjectMapper.selectById(task.getProjectId());
            BigDecimal afflicateDiscount = null;
            if (project.getIsAfflicateDiscount() == 1) {
                afflicateDiscount = new BigDecimal(project.getAfflicateDiscount());
            } else {
                R<Object> templateR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(project.getTemplateId()));
                String templateString = JSONObject.toJSONString(templateR.getData());
                ErpSellerStorePriceTemplate template = JSONObject.parseObject(templateString, ErpSellerStorePriceTemplate.class);
                afflicateDiscount = template.getUnion();
            }
            if (afflicateDiscount.compareTo(BigDecimal.ZERO) > 0) {
                //调用孙哥方法
                R<Object> commissionObjectR = remoteSellerStoreService.setCommission(project.getStoreId(), task.getAeProductId(), afflicateDiscount.intValue());
                String remark = task.getRemark();
                if (commissionObjectR.getCode() == 200) {
                    task.setStatus(2);
                    String newRemark = remark.replaceAll("请求速卖通设置失败", "子账号暂不创建联盟折扣");
                    task.setRemark(newRemark);
                    erpAutoPulishProductProjectTaskMapper.updateById(task);
                } else {
                    System.out.println(commissionObjectR.getMsg());
                    String newRemark = remark.replaceAll("请求速卖通设置失败", commissionObjectR.getMsg());
                    task.setRemark(newRemark);
                    erpAutoPulishProductProjectTaskMapper.updateById(task);
                }
            } else {
                System.out.println("无需设置联盟折扣");
            }
        }
        return R.ok();
    }

    @Override
    public AeAutoProductDto reissueMessageQueue(ErpAutoPulishProductProjectTask task) {
        // 1、上传速卖通之前判断是否合规
        ErpAutoPulishProductProject project = erpAutoPulishProductProjectMapper.selectById(task.getProjectId());
        //存入所需要参数
        AeAutoProductDto dto = new AeAutoProductDto();
        if (ObjectUtils.isNull(project.getProductDiscountId())) {
            task.setPublishTime(DateUtils.getTime());
            task.setStatus(3);
            task.setAeProductId(dto.getAeProductId());
            task.setRemark("计划未创建活动");
            dto.setCode(500);
            dto.setMsg("计划未创建活动");
            erpAutoPulishProductProjectTaskMapper.updateById(task);
            return dto;
        } else {
            dto.setProductDiscountId(project.getProductDiscountId());
        }
        dto.setSellerId(project.getUserId());
        dto.setStoreUserName(project.getStoreUserName());
        dto.setActivityId(project.getProductDiscountId());
        dto.setProductBrand(project.getProductBrand());
        dto.setAutoTaskId(task.getId().toString());
        dto.setStoreId(task.getStoreId());
        dto.setCollectProductId(task.getCollectProductId());
        dto.setTemplateId(project.getTemplateId());
        dto.setIsAfflicateDiscount(project.getIsAfflicateDiscount());
        dto.setAfflicateDiscount(project.getAfflicateDiscount());

        dto.setProductType(task.getProductType());
        if (ObjectUtils.isNull(dto.getMethodType())) {
            //与是否设置联盟折扣相关 为0则不进行设置，为1则进行设置
            //不为测试发布时,是子账号则不标记为0
            ErpAutoSellerStoreConfig storeConfig = erpAutoSellerStoreConfigMapper.selectOne(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfig>().eq(ErpAutoSellerStoreConfig::getStoreId, dto.getStoreId())
            );
            if (ObjectUtils.isNotNull(storeConfig)) {
                //获取店铺名称，确认是否为子账号
                String storeAile = storeConfig.getStoreAlias();
                if (storeAile.contains("子账号")) {
                    dto.setStoreType(0);
                } else {
                    dto.setStoreType(1);
                }
            } else {
                dto.setStoreType(1);
            }
        } else {
            dto.setStoreType(0);
        }


        //根据类型进行判断，获取所需要的数据
        if (Objects.isNull(task.getProductType()) || task.getProductType() == 0) {
            task.setProductType(0);
            //原厂数据
            // 确认是否已被公共库删除
            R<Object> collectProductObject = remoteCollectProductService.getCollectProductInfoById(task.getCollectProductId());
            String collectProductJSONString = JSONObject.toJSONString(collectProductObject.getData());
            ErpCollectProduct collectProduct = JSONObject.parseObject(collectProductJSONString, ErpCollectProduct.class);
            if (collectProduct.getDelFlag().equals("2")) {
                task.setStatus(3);
                task.setRemark("商品已被删除");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                dto.setCode(500);
                dto.setMsg("商品已被删除");
                return dto;
            }

            // 确认是否已被公共库下架
            ErpCollectProductExpand collectProductExpandSel = new ErpCollectProductExpand();
            collectProductExpandSel.setCollectProductId(task.getCollectProductId());
            R<Object> collectProductExpandObject = remoteCollectProductService.getCollectProductExpandInfo(collectProductExpandSel);
            String collectProductExpandJSONString = JSONObject.toJSONString(collectProductExpandObject.getData());
            ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(collectProductExpandJSONString, ErpCollectProductExpand.class);
            if (collectProductExpand.getProductStatus() == 0) {
                task.setStatus(3);
                task.setRemark("商品已下架");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                dto.setCode(500);
                dto.setMsg("商品已下架");
                return dto;
            }
            ErpCollectProductSku erpCollectProductSkuSel = new ErpCollectProductSku();
            erpCollectProductSkuSel.setCollectProductId(task.getCollectProductId());
            R<Object> collectProductSkuObject = remoteCollectProductService.getCollectProductSkuListInfo(erpCollectProductSkuSel);
            String collectProductSkuJSONString = JSONObject.toJSONString(collectProductSkuObject.getData());
            List<ErpCollectProductSkuVo> skuList = JSONArray.parseArray(collectProductSkuJSONString, ErpCollectProductSkuVo.class);

            //获取
            dto.setCollectProduct(collectProduct);
            dto.setCollectProductExpand(collectProductExpand);
            dto.setCollectProductSkuList(skuList);
        } else {
            //collectProductA数据
            R<Object> collectProductAObject = remoteCollectProductAService.getCollectProductAAllInfoById(task.getCollectProductId());
            if (collectProductAObject.getCode() != 200) {
                task.setStatus(3);
                task.setRemark("查找该产品相关信息异常");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                dto.setCode(500);
                dto.setMsg("查找该产品相关信息异常");
                return dto;
            }
            String collectProductAJSONString = JSONObject.toJSONString(collectProductAObject.getData());
            ComputeFreightDto computeFreightDto = JSONObject.parseObject(collectProductAJSONString, ComputeFreightDto.class);
            ErpCollectProduct collectProduct = JSONObject.parseObject(computeFreightDto.getProduct().toString(), ErpCollectProduct.class);
            ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(computeFreightDto.getProductExpand().toString(), ErpCollectProductExpand.class);
            List<ErpCollectProductSkuVo> skuList = JSONArray.parseArray(computeFreightDto.getProductSkuList().toString(), ErpCollectProductSkuVo.class);

            dto.setCollectProduct(collectProduct);
            dto.setCollectProductExpand(collectProductExpand);
            dto.setCollectProductSkuList(skuList);
        }


        //判断商品前置条件是否满足
        R<Object> judgeR = judgeProduct(dto, 1);
        if (judgeR.getCode() != 200) {
            task.setStatus(3);
            task.setRemark(judgeR.getMsg().toString());
            erpAutoPulishProductProjectTaskMapper.updateById(task);
            dto.setCode(500);
            dto.setMsg(judgeR.getMsg());
            return dto;
        }
        System.out.println("----------补发消息队列计划" + task.getId() + "开始执行-------------");
        // 开始上传至速卖通
        R<Object> aeProductR = remotePublishProductService.reissueMessageQueue(dto);
        String aeProductString = JSONObject.toJSONString(aeProductR.getData());
        dto = JSONObject.parseObject(aeProductString, AeAutoProductDto.class);
        return dto;
    }


    @Override
    public Boolean getTaskByProductId(Long aeProductId) {
        ErpAutoPulishProductProjectTask task = erpAutoPulishProductProjectTaskMapper.selectOne(new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>().eq(ErpAutoPulishProductProjectTask::getAeProductId, aeProductId));
        if (task == null) {
            task = erpAutoPulishProductProjectTaskMapper.selectOneOld(aeProductId);
            return task != null;
        }
        return true;
    }

    @Async("auto")
    @Override
    public Future<AeAutoProductDto> runPublishProductToAe(ErpAutoPulishProductProjectTask task) {
        // 1、上传速卖通之前判断是否合规
        ErpAutoPulishProductProject project = erpAutoPulishProductProjectMapper.selectById(task.getProjectId());
        //存入所需要参数
        AeAutoProductDto dto = new AeAutoProductDto();
        if (ObjectUtils.isNull(project.getProductDiscountId())) {
            task.setPublishTime(DateUtils.getTime());
            task.setStatus(3);
            task.setAeProductId(dto.getAeProductId());
            task.setRemark("计划未创建活动");
            dto.setCode(500);
            dto.setMsg("计划未创建活动");
            erpAutoPulishProductProjectTaskMapper.updateById(task);
            return new AsyncResult<>(dto);
        } else {
            dto.setProductDiscountId(project.getProductDiscountId());
        }
        dto.setSellerId(project.getUserId());
        dto.setStoreUserName(project.getStoreUserName());
        dto.setActivityId(project.getProductDiscountId());
        dto.setProductBrand(project.getProductBrand());
        dto.setAutoTaskId(task.getId().toString());
        dto.setStoreId(task.getStoreId());
        dto.setCollectProductId(task.getCollectProductId());
        dto.setTemplateId(project.getTemplateId());
        dto.setIsAfflicateDiscount(project.getIsAfflicateDiscount());
        dto.setAfflicateDiscount(project.getAfflicateDiscount());

        dto.setProductType(task.getProductType());
        if (ObjectUtils.isNull(dto.getMethodType())) {
            //与是否设置联盟折扣相关 为0则不进行设置，为1则进行设置
            //不为测试发布时,是子账号则不标记为0
            ErpAutoSellerStoreConfig storeConfig = erpAutoSellerStoreConfigMapper.selectOne(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfig>().eq(ErpAutoSellerStoreConfig::getStoreId, dto.getStoreId())
            );
            if (ObjectUtils.isNotNull(storeConfig)) {
                //获取店铺名称，确认是否为子账号
                String storeAile = storeConfig.getStoreAlias();
                if (storeAile.contains("子账号")) {
                    dto.setStoreType(0);
                } else {
                    dto.setStoreType(1);
                }
            } else {
                dto.setStoreType(1);
            }
        } else {
            dto.setStoreType(0);
        }


        //根据类型进行判断，获取所需要的数据
        if (Objects.isNull(task.getProductType()) || task.getProductType() == 0) {
            task.setProductType(0);
            //原厂数据
            // 确认是否已被公共库删除
            R<Object> collectProductObject = remoteCollectProductService.getCollectProductInfoById(task.getCollectProductId());
            String collectProductJSONString = JSONObject.toJSONString(collectProductObject.getData());
            ErpCollectProduct collectProduct = JSONObject.parseObject(collectProductJSONString, ErpCollectProduct.class);
            if (collectProduct.getDelFlag().equals("2")) {
                task.setStatus(3);
                task.setRemark("商品已被删除");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                dto.setCode(500);
                dto.setMsg("商品已被删除");
            }

            // 确认是否已被公共库下架
            ErpCollectProductExpand collectProductExpandSel = new ErpCollectProductExpand();
            collectProductExpandSel.setCollectProductId(task.getCollectProductId());
            R<Object> collectProductExpandObject = remoteCollectProductService.getCollectProductExpandInfo(collectProductExpandSel);
            String collectProductExpandJSONString = JSONObject.toJSONString(collectProductExpandObject.getData());
            ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(collectProductExpandJSONString, ErpCollectProductExpand.class);
            if (collectProductExpand.getProductStatus() == 0) {
                task.setStatus(3);
                task.setRemark("商品已下架");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                dto.setCode(500);
                dto.setMsg("商品已下架");
                return new AsyncResult<>(dto);
            }
            ErpCollectProductSku erpCollectProductSkuSel = new ErpCollectProductSku();
            erpCollectProductSkuSel.setCollectProductId(task.getCollectProductId());
            R<Object> collectProductSkuObject = remoteCollectProductService.getCollectProductSkuListInfo(erpCollectProductSkuSel);
            String collectProductSkuJSONString = JSONObject.toJSONString(collectProductSkuObject.getData());
            List<ErpCollectProductSkuVo> skuList = JSONArray.parseArray(collectProductSkuJSONString, ErpCollectProductSkuVo.class);

            //获取
            dto.setCollectProduct(collectProduct);
            dto.setCollectProductExpand(collectProductExpand);
            dto.setCollectProductSkuList(skuList);
        } else {
            //collectProductA数据
            R<Object> collectProductAObject = remoteCollectProductAService.getCollectProductAAllInfoById(task.getCollectProductId());
            if (collectProductAObject.getCode() != 200) {
                task.setStatus(3);
                task.setRemark("查找该产品相关信息异常");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                dto.setCode(500);
                dto.setMsg("查找该产品相关信息异常");
                return new AsyncResult<>(dto);
            }
            String collectProductAJSONString = JSONObject.toJSONString(collectProductAObject.getData());
            ComputeFreightDto computeFreightDto = JSONObject.parseObject(collectProductAJSONString, ComputeFreightDto.class);
            ErpCollectProduct collectProduct = JSONObject.parseObject(computeFreightDto.getProduct().toString(), ErpCollectProduct.class);
            ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(computeFreightDto.getProductExpand().toString(), ErpCollectProductExpand.class);
            List<ErpCollectProductSkuVo> skuList = JSONArray.parseArray(computeFreightDto.getProductSkuList().toString(), ErpCollectProductSkuVo.class);

            dto.setCollectProduct(collectProduct);
            dto.setCollectProductExpand(collectProductExpand);
            dto.setCollectProductSkuList(skuList);
        }


        try {
            //判断商品前置条件是否满足
            R<Object> judgeR = judgeProduct(dto, 0);
            if (judgeR.getCode() != 200) {
                task.setStatus(3);
                task.setRemark(judgeR.getMsg().toString());
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                dto.setCode(500);
                dto.setMsg(judgeR.getMsg());
                return new AsyncResult<>(dto);
            }

            System.out.println("----------上架计划" + task.getId() + "开始执行-------------");
            // 开始上传至速卖通
            R<Object> aeProductR = remotePublishProductService.publishAeProduct(dto);
            //将上架后时间放入task
            task.setPublishTime(DateUtils.getTime());
            if (aeProductR.getCode() != 200) {
                //上传失败
                task.setStatus(3);
                dto.setCode(500);
                String aeProductString = JSONObject.toJSONString(aeProductR.getMsg());
                dto.setMsg(aeProductString);
                task.setRemark(aeProductString);
                System.out.println("----------上架计划" + task.getId() + "执行完成-------------");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                return new AsyncResult<>(dto);
            } else {
                String aeProductString = JSONObject.toJSONString(aeProductR.getData());
                dto = JSONObject.parseObject(aeProductString, AeAutoProductDto.class);
                //上传成功
                task.setStatus(2);
                task.setAeProductId(dto.getAeProductId());
                task.setRemark("上传成功");
                dto.setCode(200);
                dto.setMsg("上传成功");
                System.out.println("----------上架计划" + task.getId() + "执行完成-------------");
                erpAutoPulishProductProjectTaskMapper.updateById(task);
                return new AsyncResult<>(dto);
            }
        } catch (Exception e) {
            task.setPublishTime(DateUtils.getTime());
            task.setStatus(3);
            task.setAeProductId(dto.getAeProductId());
            task.setRemark("异常结束");
            dto.setCode(500);
            dto.setMsg("异常结束");
            erpAutoPulishProductProjectTaskMapper.updateById(task);
            return new AsyncResult<>(dto);
        }


    }

    @Override
    public R<Object> runPublishTestProductToAe(Long collectProductId, Integer type) {
        R<Object> collectProductAObject = null;
        //0-2.0的品 1-1688品 2-wwb
        if (type == 1) {
            collectProductAObject = remoteCollectProductAService.getCollectProductAAllInfoById(collectProductId);
        } else if (type == 2) {
            collectProductAObject = remoteCollectProductBService.getCollectProductBAllInfoById(collectProductId);
        }
        if (collectProductAObject.getCode() != 200) {
            return R.fail("没有需要测试发布的商品");
        }
        String collectProductAJSONString = JSONObject.toJSONString(collectProductAObject.getData());
        ComputeFreightDto computeFreightDto = JSONObject.parseObject(collectProductAJSONString, ComputeFreightDto.class);
        ErpCollectProduct collectProduct = JSONObject.parseObject(computeFreightDto.getProduct().toString(), ErpCollectProduct.class);
        ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(computeFreightDto.getProductExpand().toString(), ErpCollectProductExpand.class);
        List<ErpCollectProductSkuVo> skuList = JSONArray.parseArray(computeFreightDto.getProductSkuList().toString(), ErpCollectProductSkuVo.class);

        List<Long> sellerStoreList = remoteProductCategoryBrandService.getCategoryTreeListForStore(collectProduct.getCategoryId());

        AeAutoProductDto dto = new AeAutoProductDto();
        dto.setCollectProduct(collectProduct);
        dto.setCollectProductExpand(collectProductExpand);
        dto.setCollectProductSkuList(skuList);
        dto.setPublishType(9);

        dto.setCollectProductId(collectProductId);
        dto.setIsAfflicateDiscount(1);
        dto.setAfflicateDiscount("8.00");

        for (Long storeId : sellerStoreList) {
//            ErpSellerStoreEmpowerExtend storeExtendSel = new ErpSellerStoreEmpowerExtend();
//            storeExtendSel.setSellerId(storeId);
//            storeExtendSel.setType(1);
//            R<Object> storeExtendObject = remoteSellerStoreService.getSellerStoreExtendInfo(storeExtendSel);
//            String storeExtendString = JSONObject.toJSONString(storeExtendObject.getData());
//            System.out.println(storeExtendString);
//            storeExtendSel = JSONObject.parseObject(storeExtendString, ErpSellerStoreEmpowerExtend.class);
//            if (Objects.isNull(storeExtendSel)) {
//                return R.fail("店铺资质信息异常");
//            }

            R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(storeId);
            String toJSONString = JSONObject.toJSONString(objectR.getData());
            ErpSellerStoreEmpower store = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);
            if (Objects.isNull(store)) {
                return R.fail("店铺不存在");
            }
            dto.setSellerId(store.getUserId());
            dto.setStoreUserName(store.getStoreUserName());
            dto.setStoreId(store.getId());

//        dto.setTemplateId(project.getTemplateId());
            try {
                //判断商品前置条件是否满足
                R<Object> judgeR = judgeProductByUploadTest(dto);
                if (judgeR.getCode() != 200) {
                    System.out.println(judgeR.getMsg().toString());
                    dto.setCode(500);
                    dto.setMsg(judgeR.getMsg());
                    return R.ok(dto);
                }

                System.out.println("----------测试发布" + collectProductId + "开始执行-------------");
                // 开始上传至速卖通
                dto.setMethodType(1);
                R<Object> aeProductR = remotePublishProductService.publishAeProduct(dto);
                if (aeProductR.getCode() != 200) {
                    //上传失败
                    dto.setCode(500);
                    String aeProductString = JSONObject.toJSONString(aeProductR.getMsg());
                    dto.setMsg(aeProductString);
                    System.out.println("----------测试发布" + collectProductId + "执行失败-------------");
                } else {
                    String aeProductString = JSONObject.toJSONString(aeProductR.getData());
                    dto = JSONObject.parseObject(aeProductString, AeAutoProductDto.class);
                    //上传成功
                    dto.setCode(200);
                    dto.setMsg("上传成功");
                    System.out.println("----------测试发布" + collectProductId + "执行完成-------------");
                }
            } catch (Exception e) {
                dto.setCode(500);
                dto.setMsg("异常结束");
            }


            if (dto.getCode() == 200) {
                //删除测试发布成功的商品
//                remoteAeProductService.deleteProductToAe(dto.getAeProductId(), dto.getStoreId());
                //标记erp_collect_product_distribute_log 测试发布成功 结果
                remoteCollectProductAService.sendCollectUpdateResult(collectProductId, 1, dto.getMsg());

            } else {
                //标记erp_collect_product_distribute_log 测试发布失败
                //记录原因到erp_collect_product_distribute_log表
                //删除erp_collect_product_a 三表中对应数据
                remoteCollectProductAService.sendCollectUpdateResult(collectProductId, 0, dto.getMsg());
            }
            return R.ok(dto);
        }

        return R.ok("测试发布完成");
    }

    /**
     * 检测活动设置异常，调用爬虫接口重新设置活动 并处理
     *
     * @return
     */
    @Override
    public R<Object> checkActivityErrorHandle() {
        //1、找到活动设置异常的任务
        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .like(ErpAutoPulishProductProjectTask::getRemark, "商品发布成功，活动设置异常")
        );

        //获取所有的执行计划，放到map里
        List<ErpAutoPulishProductProject> projectList = erpAutoPulishProductProjectMapper.selectErrorActivityList();
        Map<Long, Object> projectMap = new HashMap<>();
        for (ErpAutoPulishProductProject project : projectList) {
            projectMap.put(project.getId(), project);
        }


        //2、调用爬虫接口，重新设置活动
        if (taskList.size() == 0) {
            return R.ok("没有需要重新设置的活动");
        } else {

            for (ErpAutoPulishProductProjectTask task : taskList) {
                ErpAutoPulishProductProject project = (ErpAutoPulishProductProject) projectMap.get(task.getProjectId());
                if (Objects.isNull(project)) {
                    project = erpAutoPulishProductProjectMapper.selectById(task.getProjectId());
                }
                String remark = task.getRemark();
                //调用接口，重设活动

                R<Object> objectR = remotePythonMethodCallService.addProductToActivity(
                        task.getStoreId().toString(),
                        project.getProductDiscount(),
                        project.getProductDiscountId().toString(),
                        task.getAeProductId().toString()
                );
                if (objectR.getCode() == 200) {
                    //设置成功
                    task.setStatus(2);
                    String newRemark = remark.replaceAll("商品发布成功，活动设置异常", "活动设置完成");
                    task.setRemark(newRemark);
                    //设置成功
                } else {
                    task.setStatus(666);
                    task.setRemark(objectR.getMsg().toString());
                }
                erpAutoPulishProductProjectTaskMapper.updateById(task);

            }


        }

        return null;
    }

    /**
     * 上传速卖通之前判断是否合规
     * 0-发布时 1-补发时
     *
     * @param autoProductDto
     * @return
     */
    private R<Object> judgeProduct(AeAutoProductDto autoProductDto, Integer type) {
        //取得商品信息和延伸表信息
        ErpCollectProduct collectProduct = autoProductDto.getCollectProduct();
        ErpCollectProductExpand collectProductExpand = autoProductDto.getCollectProductExpand();

        Long storeId = autoProductDto.getStoreId();
        //判断 店铺是否有授权
        R<Object> objectR1 = remoteAeStoreInfoService.querySellerStoreInfo(storeId.toString());
        if (objectR1.getCode() != 200) {
            return R.fail("店铺授权信息异常或过期");
        }
        autoProductDto.setPublishType(type);
        if (type == 0) {
            //从在线表中查看
            R<Object> productObject = remoteSellerStoreProductService.selectRepeatProduct(autoProductDto.getStoreUserName(), autoProductDto.getCollectProductId());
            if (productObject.getCode() != 200) {
//                String productString = JSONObject.toJSONString(productObject.getData());
//                ErpSellerStoreProduct product = JSONObject.parseObject(productString, ErpSellerStoreProduct.class);
//                if (product != null) {
                // 产品发布个人产品记录日志数据为发布失败
                return R.fail("该品已存在，请勿重复发布");
//                }
            }
        }


        ErpSellerStoreEmpowerExtend storeExtendSel = new ErpSellerStoreEmpowerExtend();
        storeExtendSel.setSellerId(storeId);
        storeExtendSel.setType(1);
        R<Object> storeExtendObject = remoteSellerStoreService.getSellerStoreExtendInfo(storeExtendSel);
        String storeExtendString = JSONObject.toJSONString(storeExtendObject.getData());
        storeExtendSel = JSONObject.parseObject(storeExtendString, ErpSellerStoreEmpowerExtend.class);
        if (Objects.isNull(storeExtendSel)) {
            return R.fail("店铺资质信息异常");
        }

        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(storeId);
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStoreEmpower store = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);
        if (Objects.isNull(store)) {
            return R.fail("店铺不存在");
        }

        //目标id
        String productId = autoProductDto.getCollectProductId().toString();
        //确认是否已经被全网下架
        ErpProductUnifiedTakedown erpProductUnifiedTakedown = new ErpProductUnifiedTakedown();
        erpProductUnifiedTakedown.setCollectProductId(Long.valueOf(productId));
        erpProductUnifiedTakedown.setIsEffective(1);
        erpProductUnifiedTakedown.setIsExecute(1);
        R<Object> takedownListObject = remoteCollectProductService.getProductUnifiedTakedownListInfo(erpProductUnifiedTakedown);
        String takedownListJSONString = JSONObject.toJSONString(takedownListObject.getData());
        List<ErpProductUnifiedTakedown> takedownList = JSONArray.parseArray(takedownListJSONString, ErpProductUnifiedTakedown.class);

        if (takedownList.size() > 0) {
            return R.fail("该商品已被全网下架");
        }

        // 确认是否存在店铺活动
        ErpSellerStorePromotionActivity activitySel = new ErpSellerStorePromotionActivity();
        activitySel.setPromotionId(autoProductDto.getProductDiscountId().toString());
        R<Object> activityObject = remoteSellerStoreService.getPromotionActivityInfo(activitySel);
        String sellerStoreProductString = JSONObject.toJSONString(activityObject.getData());
        ErpSellerStorePromotionActivity activity = JSONObject.parseObject(sellerStoreProductString, ErpSellerStorePromotionActivity.class);
        if (Objects.isNull(activity)) {
            return R.fail("店铺活动不存在");
        }
        // 确认商品是否有品牌，没有则设置一个泛品牌
        R<Object> storeBrandR = remoteSellerStoreService.queryStoreBrandInnerAuth(collectProduct.getCategoryId(), autoProductDto.getCollectProductId(), autoProductDto.getStoreId());
        ErpStoreCategoryBrand storeBrand = null;
        if (storeBrandR.getCode() == 200) {
            String storeBrandRString = JSONObject.toJSONString(storeBrandR.getData());
            storeBrand = JSONObject.parseObject(storeBrandRString, ErpStoreCategoryBrand.class);
            String brandId = storeBrand.getBrandId().toString();
            autoProductDto.setProductBrand(brandId);
        } else {
            //保存该品牌至无品牌类目中
            List<ErpAutoSellerStoreConfigErrorCategory> categoryList = erpAutoSellerStoreConfigErrorCategoryMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfigErrorCategory>()
                            .eq(ErpAutoSellerStoreConfigErrorCategory::getStoreId, storeId)
                            .eq(ErpAutoSellerStoreConfigErrorCategory::getCategoryId, collectProduct.getCategoryId())
            );
            if (categoryList.size() == 0) {
                ErpAutoSellerStoreConfigErrorCategory storeConfigErrorCategory = new ErpAutoSellerStoreConfigErrorCategory();
                storeConfigErrorCategory.setStoreId(storeId);
                storeConfigErrorCategory.setStoreAlias(autoProductDto.getStoreUserName());
                storeConfigErrorCategory.setCreateTime(new Date());
                storeConfigErrorCategory.setCategoryId(collectProduct.getCategoryId());
                erpAutoSellerStoreConfigErrorCategoryMapper.insert(storeConfigErrorCategory);
            }
            return R.fail(storeId, storeBrandR.getMsg());
        }

        // 确认速卖通店铺中是否有该品牌
//        if (StringUtils.isNotEmpty(autoProductDto.getProductBrand())) {
//            Boolean bool = true;
//            // 判断是否有这个品牌 TODO 补充remote方法
//            List<Aliexpress.ValueVo> valueList = getBrandById(storeBrand.getCategoryId(), storeId);
//            if (valueList == null || valueList.size() == 0) {
//                return R.fail("速卖通店铺中没有匹配的品牌");
//            } else {
//                for (Aliexpress.ValueVo valueVo : valueList) {
//                    if (valueVo.getAttr_value_id().toString().equals(storeBrand.getCategoryId()))
//                        bool = false;
//                }
//                if (bool) {
//                    Aliexpress.ValueVo valueVo = valueList.get(0);
//                    autoProductDto.setProductBrand(valueVo.getAttr_value_id().toString());
//                }
//            }
        autoProductDto.setBrandStr("[{\"attr_name\":\"\",\"attr_name_id\":2,\"attr_value_id\":" + autoProductDto.getProductBrand() + "},");
//        }


        // 自动匹配运费模板
        // 获取系统预制的运费模板标识
        Integer settingFreightTemplateId = collectProductExpand.getTemplateId();
        if (ObjectUtils.isNull(settingFreightTemplateId)) {
            return R.fail("商品没有系统预制的运费模板标识");
        }
//                String mbName = dictService.getDictValue("erp_freight_template", settingFreightTemplateId + "");
        String mbName = new String();
        if (autoProductDto.getProductType() == 0) {
            //原库
            R<Object> mbNameObject = remoteDictDataService.getDictValue("erp_freight_template", settingFreightTemplateId + "");
            mbName = mbNameObject.getData().toString();
        } else {
            //1688采集库
            R<Object> mbNameObject = remoteDictDataService.getDictValue("erp_freight_64_template", settingFreightTemplateId + "");
            mbName = mbNameObject.getData().toString();
        }

        // 判断用哪个运费模板
        if (StringUtils.isEmpty(mbName)) { // 没有模板发布失败
            return R.fail("没有匹配的运费模板");
        }

        // 根据店铺id和固定模板名字获取运费模板id
        R<Object> freightTemplateObject = remoteSellerStoreFreightTemplateService.getFreightTemplateOneByStoreIdAndName(storeId, mbName);
        String freightTemplateString = JSONObject.toJSONString(freightTemplateObject.getData());
        ErpSellerStoreFreightTemplate freightTemplate = JSONObject.parseObject(freightTemplateString, ErpSellerStoreFreightTemplate.class);
        if (freightTemplate == null) {
            // 没有模板，先同步一下，防止没有同步发布失败
            remoteSellerStoreFreightTemplateService.getSellerStoreFreightTemplate(storeId);
            //再获取一次
            freightTemplateObject = remoteSellerStoreFreightTemplateService.getFreightTemplateOneByStoreIdAndName(storeId, mbName);
            toJSONString = JSONObject.toJSONString(freightTemplateObject.getData());
            freightTemplate = JSONObject.parseObject(toJSONString, ErpSellerStoreFreightTemplate.class);
            if (freightTemplate == null) { // 同步了还是没有，发布失败
                return R.fail("速卖通没有匹配的运费模板");
            }
        } else {
            autoProductDto.setFreightTemplateId(freightTemplate.getTemplateId()); // 运费模板
        }

        // 查看该店铺是否拥有该分类发布权限
        /*

        if (!checkStoreSubCategory(collectProduct, autoProductDto.getStoreId())) {
            // 返回false，判断true
            return R.fail("该店铺没有该分类的发布权限");
        }

        */

        return R.ok();
    }

    private R<Object> judgeProductByUploadTest(AeAutoProductDto autoProductDto) {
        ErpCollectProduct collectProduct = autoProductDto.getCollectProduct();
        ErpCollectProductExpand collectProductExpand = autoProductDto.getCollectProductExpand();
        List<ErpCollectProductSkuVo> collectProductSkuList = autoProductDto.getCollectProductSkuList();

        Long storeId = autoProductDto.getStoreId();
        //判断 店铺是否有授权
        R<Object> objectR1 = remoteAeStoreInfoService.querySellerStoreInfo(storeId.toString());
        if (objectR1.getCode() != 200) {
            return R.fail("店铺授权信息异常或过期");
        }

        //目标id
        String productId = autoProductDto.getCollectProductId().toString();

        // 确认是否已被公共库下架
//        ErpCollectProductExpand collectProductExpandSel = new ErpCollectProductExpand();
//        collectProductExpandSel.setCollectProductId(Long.valueOf(productId));
//        R<Object> collectProductExpandObject = remoteCollectProductService.getCollectProductExpandInfo(collectProductExpandSel);
//        String collectProductExpandJSONString = JSONObject.toJSONString(collectProductExpandObject.getData());
//        ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(collectProductExpandJSONString, ErpCollectProductExpand.class);
//
//        if (collectProductExpand.getProductStatus() == 0) {
//            return R.fail("商品已下架");
//        }

        // 确认商品是否有品牌，没有则设置一个泛品牌
        R<Object> storeBrandR = remoteSellerStoreService.queryStoreBrandInnerAuth(collectProduct.getCategoryId(), autoProductDto.getCollectProductId(), autoProductDto.getStoreId());
        ErpStoreCategoryBrand storeBrand = null;
        if (storeBrandR.getCode() == 200) {
            String storeBrandRString = JSONObject.toJSONString(storeBrandR.getData());
            storeBrand = JSONObject.parseObject(storeBrandRString, ErpStoreCategoryBrand.class);
            String brandId = storeBrand.getBrandId().toString();
            autoProductDto.setProductBrand(brandId);
        } else {
            //保存该品牌至无品牌类目中
            List<ErpAutoSellerStoreConfigErrorCategory> categoryList = erpAutoSellerStoreConfigErrorCategoryMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfigErrorCategory>()
                            .eq(ErpAutoSellerStoreConfigErrorCategory::getStoreId, storeId)
                            .eq(ErpAutoSellerStoreConfigErrorCategory::getCategoryId, collectProduct.getCategoryId())
            );
            if (categoryList.size() == 0) {
                ErpAutoSellerStoreConfigErrorCategory storeConfigErrorCategory = new ErpAutoSellerStoreConfigErrorCategory();
                storeConfigErrorCategory.setStoreId(storeId);
                storeConfigErrorCategory.setStoreAlias(autoProductDto.getStoreUserName());
                storeConfigErrorCategory.setCreateTime(new Date());
                storeConfigErrorCategory.setCategoryId(collectProduct.getCategoryId());
                erpAutoSellerStoreConfigErrorCategoryMapper.insert(storeConfigErrorCategory);
            }
            return R.fail(storeId, storeBrandR.getMsg());
        }

        // 确认速卖通店铺中是否有该品牌
//        if (StringUtils.isNotEmpty(autoProductDto.getProductBrand())) {
//            Boolean bool = true;
//            // 判断是否有这个品牌 TODO 补充remote方法
//            List<Aliexpress.ValueVo> valueList = getBrandById(storeBrand.getCategoryId(), storeId);
//            if (valueList == null || valueList.size() == 0) {
//                return R.fail("速卖通店铺中没有匹配的品牌");
//            } else {
//                for (Aliexpress.ValueVo valueVo : valueList) {
//                    if (valueVo.getAttr_value_id().toString().equals(storeBrand.getCategoryId()))
//                        bool = false;
//                }
//                if (bool) {
//                    Aliexpress.ValueVo valueVo = valueList.get(0);
//                    autoProductDto.setProductBrand(valueVo.getAttr_value_id().toString());
//                }
//            }
        autoProductDto.setBrandStr("[{\"attr_name\":\"\",\"attr_name_id\":2,\"attr_value_id\":" + autoProductDto.getProductBrand() + "},");
//        }


        // 自动匹配运费模板
        // 获取系统预制的运费模板标识
//        Integer settingFreightTemplateId = collectProductExpand.getTemplateId();
//        if (ObjectUtils.isNull(settingFreightTemplateId)) {
//            return R.fail("商品没有系统预制的运费模板标识");
//        }
//                String mbName = dictService.getDictValue("erp_freight_template", settingFreightTemplateId + "");
//        R<Object> mbNameObject = remoteDictDataService.getDictValue("erp_freight_template", settingFreightTemplateId + "");
//        String mbName = mbNameObject.getData().toString();
//        // 判断用哪个运费模板
//        if (StringUtils.isEmpty(mbName)) { // 没有模板发布失败
//            return R.fail("没有匹配的运费模板");
//        }
        // 根据店铺id和固定模板名字获取运费模板id
        String mbName = "P3普货";
        R<Object> freightTemplateObject = remoteSellerStoreFreightTemplateService.getFreightTemplateOneByStoreIdAndName(storeId, mbName);
        String freightTemplateString = JSONObject.toJSONString(freightTemplateObject.getData());
        ErpSellerStoreFreightTemplate freightTemplate = JSONObject.parseObject(freightTemplateString, ErpSellerStoreFreightTemplate.class);
        if (freightTemplate == null) {
            // 没有模板，先同步一下，防止没有同步发布失败
            remoteSellerStoreFreightTemplateService.getSellerStoreFreightTemplate(storeId);
            //再获取一次
            freightTemplateObject = remoteSellerStoreFreightTemplateService.getFreightTemplateOneByStoreIdAndName(storeId, mbName);
            String toJSONString = JSONObject.toJSONString(freightTemplateObject.getData());
            freightTemplate = JSONObject.parseObject(toJSONString, ErpSellerStoreFreightTemplate.class);
            if (freightTemplate == null) { // 同步了还是没有，发布失败
                return R.fail("速卖通没有匹配的运费模板");
            }
        } else {
            autoProductDto.setFreightTemplateId(freightTemplate.getTemplateId()); // 运费模板
        }

        // 查看该店铺是否拥有该分类发布权限
        /*

        if (!checkStoreSubCategory(collectProduct, autoProductDto.getStoreId())) {
            // 返回false，判断true
            return R.fail("该店铺没有该分类的发布权限");
        }

        */

        return R.ok();
    }


//    @Override
//    public R<Object> runPulishProductProjectTaskJob(String id, String projectId) {
//        List<ErpAutoPulishProductProjectTask> taskList = new ArrayList<>();
//        if (ObjectUtils.isNull(id)) {
//            //获取当前需要执行的任务列表
//            //待执行的，且时间在当前时间到当前时间+1分钟之间的
//            //获取当前时间
//            LocalDateTime now = LocalDateTime.now();
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 格式化当前时间
//            String nowFormatted = now.format(formatter);
//            LocalDateTime parse = LocalDateTime.parse(nowFormatted, formatter);
////            LocalDateTime oneDayLater = parse.plusDays(-2);
//            LocalDateTime zeroHour = parse.withHour(0).withMinute(0).withSecond(0).withNano(0);
//            String startDate = zeroHour.toString();
////            Date date = DateUtils.addMinutes(new Date(), 1);
////            // 定义日期格式化字符串
////            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////            // 将Date对象转换为字符串
////            String endDate = formatter.format(date);
//
//            String endDate = DateUtils.getTime();
//            List<ErpAutoPulishProductProjectTask> taskListSel = erpAutoPulishProductProjectTaskMapper.selectList(
//                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
//                            .eq(ErpAutoPulishProductProjectTask::getStatus, 1)
//                            .eq(ErpAutoPulishProductProjectTask::getProjectId, projectId)
//                            .ge(ErpAutoPulishProductProjectTask::getExecutionTime, startDate)
//                            .lt(ErpAutoPulishProductProjectTask::getExecutionTime, endDate)
//            );
//            if (taskListSel.size() > 0) {
//                return R.fail("还有正在执行的任务");
//            }
//
//            taskList = erpAutoPulishProductProjectTaskMapper.selectList(
//                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
//                            .eq(ErpAutoPulishProductProjectTask::getStatus, 0)
//                            .eq(ErpAutoPulishProductProjectTask::getProjectId, projectId)
//                            .ge(ErpAutoPulishProductProjectTask::getExecutionTime, startDate)
//                            .lt(ErpAutoPulishProductProjectTask::getExecutionTime, endDate)
//                            .last("limit 3")
//            );
//        } else {
//            taskList = erpAutoPulishProductProjectTaskMapper.selectList(
//                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
//                            .eq(ErpAutoPulishProductProjectTask::getId, id)
//            );
//        }
//
//        for (ErpAutoPulishProductProjectTask task : taskList) {
//            ErpAutoPulishProductProjectTask taskUpdate = new ErpAutoPulishProductProjectTask();
//            taskUpdate.setStatus(1);
//            erpAutoPulishProductProjectTaskMapper.update(taskUpdate,
//                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>().eq(ErpAutoPulishProductProjectTask::getId, task.getId())
//            );
//        }
//
//
//        //将这个list中的值传到erp进行处理
//        for (ErpAutoPulishProductProjectTask task : taskList) {
//            System.out.println("----------上架计划" + projectId + "开始执行-------------");
//            ErpAutoPulishProductProject project = erpAutoPulishProductProjectMapper.selectById(task.getProjectId());
//            //公共库
//            project.setProductId(task.getCollectProductId());
//
//            project.setTaskId(task.getId());
//            //查找符合条件的商品
//            R<Object> objectR = runPulishProductProjectTaskJob(project);
////            ResponseEntity<String> forEntity = restTemplate
////                    .postForEntity(erpConfig.getEndpoint() + "/gather/autoQueryInfo/runPulishProductProjectTaskJob", project, String.class);
//            String body = (String) objectR.getData();
//            JSONObject bodyJson = JSONObject.parseObject(body);
//            Integer code = bodyJson.getInteger("code");
//            if (code != 200) {
//                //失败
//                task.setStatus(3);
//                String msg = bodyJson.getString("msg");
//                String data = bodyJson.getString("data");
//                if (ObjectUtils.isNotNull(data)) {
//                    task.setRemark(msg + "|" + data);
//                } else {
//                    task.setRemark(msg);
//                }
//
//                //删除临时表数据 若不包含品牌，且不包含模版时调用
//                if (!msg.contains("品牌") && !msg.contains("模版")) {
////                    ResponseEntity<String> forEntityDel = restTemplate
////                            .getForEntity(erpConfig.getEndpoint() + "/gather/autoQueryInfo/deleteTemporaryByCollectProductId?collectProductId=" + task.getCollectProductId(), String.class);
//                }
//                //将状态改为4，且记录category，
//                if (msg.contains("品牌")) {
//                    task.setStatus(4);
//                    List<ErpAutoSellerStoreConfigErrorCategory> categoryList = erpAutoSellerStoreConfigErrorCategoryMapper.selectList(
//                            new LambdaQueryWrapper<ErpAutoSellerStoreConfigErrorCategory>()
//                                    .eq(ErpAutoSellerStoreConfigErrorCategory::getStoreId, task.getStoreId())
//                                    .eq(ErpAutoSellerStoreConfigErrorCategory::getCategoryId, data)
//                    );
//                    if (categoryList.size() == 0) {
//                        ErpAutoSellerStoreConfigErrorCategory storeConfigErrorCategory = new ErpAutoSellerStoreConfigErrorCategory();
//                        storeConfigErrorCategory.setStoreId(task.getStoreId());
//                        storeConfigErrorCategory.setStoreAlias(project.getStoreUserName());
//                        storeConfigErrorCategory.setCreateTime(new Date());
//                        storeConfigErrorCategory.setCategoryId(Long.valueOf(data));
//                        erpAutoSellerStoreConfigErrorCategoryMapper.insert(storeConfigErrorCategory);
//                    }
//                }
//
////                //设置疑似侵权
////                if (msg.contains("产品进入审核中状态")) {
////                    task.setStatus(5);
////                    restTemplate.getForEntity(erpConfig.getEndpoint() + "/gather/autoQueryInfo/signTort?collectProductId=" + task.getCollectProductId(), String.class);
////                }
//
//                erpAutoPulishProductProjectTaskMapper.updateById(task);
//                return R.fail(msg);
//            } else {
//                System.out.println(bodyJson);
//                JSONObject jsonObject = JSONObject.parseObject(bodyJson.getString("data"));
//                task.setCollectProductId(jsonObject.getLong("collectProductId"));
//                task.setSellerProductId(jsonObject.getLong("sellerProductId"));
//                task.setAeProductId(jsonObject.getLong("aeProductId"));
//                task.setRemark(jsonObject.getString("remark"));
//                task.setStatus(2);
//                erpAutoPulishProductProjectTaskMapper.updateById(task);
//            }
//
//        }
//        System.out.println("----------上架计划" + projectId + "执行完成-------------");
//        return R.ok("执行完成");
//    }


    public R<Object> runPulishProductProjectTaskJob(@NotNull @RequestBody ErpAutoPulishProductProject project) {
        // 1、刊登到个人商品库
//        R<Object> sellerProductFlag = erpAutoPublishProductProjectService.publishSellerProduct(project);
//
//        if (sellerProductFlag.getCode() != 200) {
//            return R.fail(sellerProductFlag.getData(), sellerProductFlag.getMsg());
//        }

        // 2、刊登到店铺在线商品库
//        Long sellerProductId = (Long) sellerProductFlag.getData();
        R<Object> sellerStoreProductFlag = erpAutoPublishProductProjectService.publishSellerStoreProduct(project);
        if (sellerStoreProductFlag.getCode() != 200) {
            return R.fail(sellerStoreProductFlag.getData(), sellerStoreProductFlag.getMsg());
        }

        // 3、上传至速卖通
        R<Object> aeProductFlag = erpAutoPublishProductProjectService.publishAeProduct(project);
        if (aeProductFlag.getCode() != 200) {
            return R.fail(aeProductFlag.getData(), aeProductFlag.getMsg());
        }
//        // 4、处理数据
        R<Object> endFlag = erpAutoPublishProductProjectService.processAeProduct((Long) aeProductFlag.getData(), project);
        return endFlag;
    }


    /**
     * 获取品牌id
     *
     * @param categoryId
     * @param storeId
     * @return
     */
    public List<Aliexpress.ValueVo> getBrandById(Long categoryId, Long storeId) {
        List<Aliexpress.ValueVo> values = new ArrayList<>();

        R<Object> brandR = remoteAeCategoryService.getBrandByIdInnerAuth(categoryId, storeId);
        JSONObject brando = JSONObject.parseObject((String) brandR.getData());
        String aeopAttributeDto = brando.getJSONObject("aliexpress_category_redefining_getchildattributesresultbypostcateidandpath_response")
                .getJSONObject("result")
                .getJSONObject("attributes")
                .getString("aeop_attribute_dto");
        List<Aliexpress.AttributeDto> attributeDtoList = JSONArray.parseArray(aeopAttributeDto, Aliexpress.AttributeDto.class);

        if (ObjectUtils.isNull(attributeDtoList)) {
            return values;
        }

        for (Aliexpress.AttributeDto attributeDto : attributeDtoList) {

            Long nameId = attributeDto.getId();
            if (nameId.equals(2l)) {

                List<Aliexpress.AttrValueDto> attrValueDtoList = attributeDto.getValues().getAeopAttrValueDto();
                if (attrValueDtoList != null) {
                    for (Aliexpress.AttrValueDto attrValueDto : attrValueDtoList) {
                        Aliexpress.ValueVo valueVo = new Aliexpress.ValueVo();

                        Map valueNames = JSONObject.parseObject(attrValueDto.getNames(), Map.class);
                        String enValueName = (String) valueNames.get("en");
                        String zhValueName = (String) valueNames.get("zh");

                        valueVo.setAttr_value_id(attrValueDto.getId());
                        valueVo.setZhName(zhValueName);
                        valueVo.setAttr_value(enValueName);
                        values.add(valueVo);
                    }
                }
            }
        }
        return values;
    }

    /**
     * 处理重复上货问题
     *
     * @return
     */
    @Override
    public R<Object> queryRepeatPublishErrorByStoreId(Long storeId) {
        //1、查询店铺中有哪些品是重复的
        List<String> productList = erpAutoPulishProductProjectTaskMapper.repeatPublishErrorByStoreId(storeId);
        //2、开始循环
        for (String collectProductId : productList) {
            List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getStatus, 2)
                            .eq(ErpAutoPulishProductProjectTask::getCollectProductId, collectProductId)
                            .eq(ErpAutoPulishProductProjectTask::getStoreId, storeId)
                            .orderByDesc(ErpAutoPulishProductProjectTask::getExecutionTime)
            );
            List<ErrorProductDto> dtoList = new ArrayList<>();
            for (ErpAutoPulishProductProjectTask task : taskList) {
                //3、将aeProductId作为查询点，获取erp_seller_store_commodity_rank_statistics表数据
                ErrorProductDto dto = erpAutoPulishProductProjectTaskMapper.queryRankStatisticsByStoreIdAndAeProduct(task.getAeProductId());
                if (ObjectUtils.isNotNull(dto)) {
                    dtoList.add(dto);
                }
            }
            //5、对产品进行排序
            Collections.sort(dtoList, Comparator.comparingDouble(ErrorProductDto::calculateScore).reversed());
            // 最优产品将是列表中的第一个
            ErrorProductDto bestProduct = dtoList.get(0);
            if (ObjectUtils.isNull(bestProduct.getAeProductId())) {
                //取时间最早的那一个
                bestProduct.setAeProductId(taskList.get(0).getAeProductId());
            } else {
                System.out.println(bestProduct);
            }

            //将list中数据进行标记删除
            ErpAutoPulishProductProjectTask task = new ErpAutoPulishProductProjectTask();
            task.setStatus(500);
            erpAutoPulishProductProjectTaskMapper.update(task,
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getCollectProductId, collectProductId)
                            .ne(ErpAutoPulishProductProjectTask::getAeProductId, bestProduct.getAeProductId())
                            .eq(ErpAutoPulishProductProjectTask::getStoreId, storeId)
            );
        }


        return R.ok();
    }


    /**
     * 确认是否有重复上架的品
     *
     * @return
     */
    @Override
    public R<Object> queryRepeatPublishErrorAllStore() {
        List<ErpAutoSellerStoreConfig> storeList = erpAutoSellerStoreConfigMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                        .eq(ErpAutoSellerStoreConfig::getStatus, 1)
        );
        int i = 0;
        for (ErpAutoSellerStoreConfig store : storeList) {
            i++;
            int j = storeList.size() - i;
            System.out.println("开始扫描店铺" + store.getStoreAlias());
            queryRepeatPublishErrorByStoreId(store.getStoreId());
            System.out.println("扫描店铺完成" + store.getStoreAlias() + ",剩余" + j + "个待扫描");
        }

        return R.ok();

    }


    /**
     * 将502状态的任务重新下架
     * 全店铺版
     */
    @Override
    public R<Object> unshelfRepeatErrorTaskAllStore() {
        List<ErpAutoSellerStoreConfig> storeList = erpAutoSellerStoreConfigMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                        .eq(ErpAutoSellerStoreConfig::getStatus, 1)
        );
        int i = 0;
        for (ErpAutoSellerStoreConfig store : storeList) {
            i++;
            int j = storeList.size() - i;
            System.out.println("开始扫描店铺" + store.getStoreAlias());
            unshelfRepeatErrorTaskByStoreId(store.getStoreId());
            System.out.println("扫描店铺完成" + store.getStoreAlias() + ",剩余" + j + "个待扫描");
        }
        return R.ok();
    }

    /**
     * 将502状态的任务重新下架
     * 单店铺版
     */
    private void unshelfRepeatErrorTaskByStoreId(Long storeId) {
        //1、找到status = 502 的下架失败的重复的品
        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .eq(ErpAutoPulishProductProjectTask::getStatus, 502)
                        .eq(ErpAutoPulishProductProjectTask::getStoreId, storeId)
        );
        if (taskList.size() == 0) {
            return;
        }

        for (ErpAutoPulishProductProjectTask task : taskList) {

            //2、进行下架
            R<Object> objectR = remoteAeProductService.productOffline(task.getAeProductId(), task.getStoreId());


            if (objectR.getCode() == 200) {
                task.setStatus(503);
            } else {
                //3、分析返回的失败原因
                String msg = objectR.getMsg();
                if (!msg.contains("aliexpress_postproduct_redefining_offlineaeproduct_response")) {
                    continue;
                }
                JSONObject object = JSONObject.parseObject(msg);

                String errorDetail = object.getJSONObject("aliexpress_postproduct_redefining_offlineaeproduct_response")
                        .getJSONObject("result")
                        .getJSONObject("error_details")
                        .getString("error_detail");
                if (errorDetail.contains("Product is not online") || errorDetail.contains("Product does not exist")) {
                    //3-1、如果是已经不存在了，则设为501
                    task.setStatus(501);
                } else {
                    //3-2、如果是其他情况，不变，仍为502，具体分析
                    System.out.println(errorDetail);
                    task.setStatus(502);
                }
            }
            erpAutoPulishProductProjectTaskMapper.updateById(task);
        }
    }


    /**
     * 将501状态的任务直接删除
     * 全店铺版
     */
    @Override
    public R<Object> deleteRepeatErrorTaskAllStore() {
        List<ErpAutoSellerStoreConfig> storeList = erpAutoSellerStoreConfigMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                        .eq(ErpAutoSellerStoreConfig::getStatus, 1)
        );
        int i = 0;
        for (ErpAutoSellerStoreConfig store : storeList) {
            i++;
            int j = storeList.size() - i;
            System.out.println("开始扫描店铺" + store.getStoreAlias());
            deleteRepeatErrorTaskByStoreId(store.getStoreId());
            System.out.println("扫描店铺完成" + store.getStoreAlias() + ",剩余" + j + "个待扫描");
        }
        return R.ok();
    }

    /**
     * 将502状态的任务重新下架
     * 单店铺版
     */
    private void deleteRepeatErrorTaskByStoreId(Long storeId) {
        //1、找到status = 502 的下架失败的重复的品
        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .eq(ErpAutoPulishProductProjectTask::getStatus, 501)
                        .eq(ErpAutoPulishProductProjectTask::getStoreId, storeId)
        );
        if (taskList.size() == 0) {
            return;
        }

        for (ErpAutoPulishProductProjectTask task : taskList) {
            //503 删除成功
            //504 删除异常
            //2、进行下架
            R<Object> objectR = remoteAeProductService.deleteProductToAe(task.getAeProductId(), task.getStoreId());
            if (objectR.getCode() == 200) {
                task.setStatus(503);
            } else {
                //3、分析返回的失败原因
                String msg = objectR.getMsg();
                JSONObject object = JSONObject.parseObject(msg);

                String errorDetail = object.getJSONObject("error_response")
                        .getString("sub_msg");
                if (errorDetail.contains("Product is not online") || errorDetail.contains("Product does not exist")) {
                    //3-1、如果是已经不存在了，则设为501
                    task.setStatus(503);
                } else {
                    //3-2、如果是其他情况，不变，仍为502，具体分析
                    System.out.println(errorDetail);
                    task.setStatus(504);
                }
            }
            erpAutoPulishProductProjectTaskMapper.updateById(task);
        }
    }


}
